package org.baicaixiaozhan.learncommon.util.accesslimit;

import com.google.common.util.concurrent.RateLimiter;
import org.baicaixiaozhan.learncommon.exception.TimeOutException;

import java.util.concurrent.TimeUnit;

/**
 * DESC: 通过 guava 令牌桶 {@link RateLimiter} 来实现 API 访问限制
 *
 * @since 2021-07-01
 * @author baicaixiaozhan
 */
public class AccessWithRateLimiter implements AccessLimiter {

    private static final RateLimiter RATE_LIMITER = RateLimiter.create(1);
    public static final int TIMEOUT = 5;

    @Override
    public void startAccessLimit() {
        if (!RATE_LIMITER.tryAcquire(TIMEOUT, TimeUnit.SECONDS)) {
            throw new TimeOutException();
        }
    }
}
